package com.icloud.common.web.interceptor;

import com.icloud.common.core.constant.CommonConstant;
import com.icloud.common.web.util.I18nUtil;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;


/**
 * 国际化拦截器
 * Created by im on 2018/4/26.
 */

public class LocaleInterceptor extends LocaleChangeInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String newLocale = request.getHeader(CommonConstant.LANGUAGE_REQUEST_HEADER_KEY);
        if(newLocale != null) {
            LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
            if(localeResolver == null) {
                throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request ?");
            }
            try {
                localeResolver.setLocale(request, response, parseLocaleValue(newLocale));
            }catch (IllegalArgumentException e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
        return true;
    }

    @Override
    protected Locale parseLocaleValue(String localeValue) {
        Locale locale = I18nUtil.getCurrentLocale(localeValue);
        return locale;
    }
}
